package cn.tang.tframe.mybatis.manager;

import cn.tang.tframe.common.base.PageBean;
import cn.tang.tframe.common.exception.ValidateUtil;
import cn.tang.tframe.mybatis.mapper.BaseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;


/**
 * 业务操作基类
 * 
 * @author tanghc
 */
public class BaseManager<PK extends Serializable, E extends Serializable, C extends Serializable, D extends BaseMapper<PK, E, C>>
		implements IBaseManager<PK, E, C> {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	protected D baseMapper;

	@Autowired
	protected void setBaseDao(D baseMapper) {
		this.baseMapper = baseMapper;
	}

	@Override
	public int countByExample(C example) {
		ValidateUtil.checkNotNull(example, "条件不能为空");
		return this.baseMapper.countByExample(example);
	}

	@Transactional
	@Override
	public void deleteByPrimaryKey(PK id) {
		ValidateUtil.checkNotNull(id, "数据id不能为空");
		ValidateUtil.isTrue(this.baseMapper.deleteByPrimaryKey(id) == 1, "删除数据有误");
	}

	@Transactional
	@Override
	public void insert(E record) {
		ValidateUtil.checkNotNull(record, "删除数据不能为空");
		validateInsert(record);
		ValidateUtil.isTrue(this.baseMapper.insert(record) > 0, "保存数据有误");
	}

	@Override
	public List<E> selectByExample(C example) {
		ValidateUtil.checkNotNull(example, "条件不能为空");
		return this.baseMapper.selectByExample(example);
	}

	@Override
	public E selectByPrimaryKey(PK id) {
		ValidateUtil.checkNotNull(id, "条件不能为空");
		return this.baseMapper.selectByPrimaryKey(id);
	}

	@Override
	public PageBean<E> page(C example) {
		ValidateUtil.checkNotNull(example, "条件不能为空");
		return new PageBean<>(this.selectByExample(example), this.countByExample(example));
	}

	@Transactional
	@Override
	public void updateByPrimaryKeySelective(E record) {
		ValidateUtil.checkNotNull(record, "更新数据不能为空");
		validateUpdate(record);
		ValidateUtil.isTrue(this.baseMapper.updateByPrimaryKeySelective(record) == 1, "更新数据有误");
	}
	@Transactional
	@Override
	public void updateByExampleSelective(E record,C example) {
		ValidateUtil.checkNotNull(record, "更新数据不能为空");
		ValidateUtil.checkNotNull(example, "更新数据条件不能为空");
		validateUpdate(record);
		this.baseMapper.updateByExampleSelective(record,example);
	}

	public void validateInsert(E record){

	}
	public void validateUpdate(E record){

	}
}
